package com.yc.RSS.writer;

import com.yc.RSS.CommonInformationItem;
import com.yc.RSS.buffer.NewsBuffer;
import com.yc.RSS.dao.ProjectProperties;
import org.apache.log4j.Logger;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 从缓存中取数据   写到磁盘(mongoDB  数据库)
 * @author zwei
 * @create 2024-07-24 15:48
 */
public class NewsWriterTask implements Runnable {
    private Logger logger=Logger.getLogger(NewsWriterTask.class);
    private String name;    //RSS的源的名称   用来做磁盘文件的文件名
    private NewsBuffer buffer;  //缓存
    private boolean flag=false;   //是否结束
    public NewsWriterTask(NewsBuffer buffer){
        this.buffer=buffer;
        this.name=" 未知新闻源 ";
    }
    public NewsWriterTask(NewsBuffer buffer,String name){
        this.buffer=buffer;
        this.name=name;
    }

    @Override
    public void run() {
        //循环从buffer中去新闻  存到磁盘
        while (!flag&&!Thread.currentThread().isInterrupted()){
            CommonInformationItem item= null;
            try {
                item = buffer.get();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if (item==null){
                System.out.println("暂无数据写入");
                continue;
            }
            //将此item存到磁盘
            Path p=Paths.get(ProjectProperties.getInstance().getProperty("file.path")+ item.getFileName());
            //流     创建一个缓冲字符流(因为可以一行一行的写数据)         CREATE  每次都创建一个新的文件
            try (BufferedWriter writer= Files.newBufferedWriter(p, StandardOpenOption.CREATE)){
                writer.write(item.toString());
                writer.flush();
            } catch (IOException e) {
                logger.error("保存信息失败"+e);
            }
        }
    }
}
